package ihuotui.sample.webmagic.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClient {

    private static final String USER_AGENT =
            "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0";

    private static Logger logger = LoggerFactory.getLogger(HttpClient.class);

    private static final int TIMEOUT_SECONDS = 120;

    private static final int POOL_SIZE = 120;

    private static CloseableHttpClient httpclient;

    private static volatile HttpClient instance;

    public static void main(String[] args) throws ClientProtocolException, IOException {

        HttpClient imageDownloader = HttpClient.getInstantce();

        String imageUrl = "http://icon.nipic.com/BannerPic/20161228/original/20161228151018_1.jpg";
        // mac
        // imageDownloader.save("/Users/ihuotui/Downloads/img/log",imageUrl,"http://icon.nipic.com/");
        // win
        imageDownloader.save("D:\\Downloads\\", imageUrl, "http://icon.nipic.com/");
        // imageDownloader.destroyApacheHttpClient();
    }

    private HttpClient() {

    }

    public static HttpClient getInstantce() {
        if (instance == null) {
            synchronized (HttpClient.class) {
                if (instance == null) {
                    instance = new HttpClient();
                    instance.initApacheHttpClient();
                }
            }
        }
        return instance;
    }

    public void initApacheHttpClient() {

        // Create global request configuration
        RequestConfig defaultRequestConfig =
                RequestConfig.custom().setSocketTimeout(TIMEOUT_SECONDS * 1000)
                        .setConnectTimeout(TIMEOUT_SECONDS * 1000).build();

        // Create an HttpClient with the given custom dependencies and
        // configuration.
        httpclient = HttpClients.custom().setUserAgent(USER_AGENT).setMaxConnTotal(POOL_SIZE)
                .setMaxConnPerRoute(POOL_SIZE).setDefaultRequestConfig(defaultRequestConfig)
                .build();
    }

    @SuppressWarnings("unused")
    private void destroyApacheHttpClient() {
        try {
            httpclient.close();
        } catch (IOException e) {
            logger.error("httpclient close fail", e);
        }
    }

    public void save(String systemPath, String imageUrl, String Referer)
            throws ClientProtocolException, IOException {
        HttpGet httpget = new HttpGet(imageUrl);
        if (StringUtils.isNotBlank(Referer)) {
            httpget.setHeader("Referer", Referer);
        }
        httpget.setHeader("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        httpget.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
        CloseableHttpResponse response = httpclient.execute(httpget);

        try {
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() >= 400) {
                throw new IOException("Got bad response, error code = "
                        + response.getStatusLine().getStatusCode() + " imageUrl: " + imageUrl);
            }
            if (entity != null) {
                InputStream input = entity.getContent();

                String fileName = makeFileSystemPath(systemPath, imageUrl);

                OutputStream output = new FileOutputStream(new File(fileName));
                IOUtils.copy(input, output);
                output.flush();
            }
        } finally {
            response.close();
        }

    }

    private String makeFileSystemPath(String systemPath, String imageUrl) {
        String fileName = "";
        // mac
        if (systemPath.contains("/")) {
            fileName = systemPath;
            if (!fileName.endsWith("/")) {
                fileName = fileName + "/";
            }
        }
        // win
        if (systemPath.contains("\\")) {
            fileName = systemPath;
            if (!fileName.endsWith("\\")) {
                fileName = fileName + "\\";
            }
        }

        fileName = fileName + imageUrl.substring(imageUrl.lastIndexOf("/"));
        return fileName;
    }

    public boolean isFileExit(String systemPath, String imageUrl) {
        String fileName = makeFileSystemPath(systemPath, imageUrl);;
        File file = new File(fileName);
        if (file.exists()) {
            return true;
        } else {
            return false;
        }
    }
}
